from SQLConfig import db


# 用户数据表
class Users(db.Model):
    """
    用户数据表
    """
    __table_args__ = {'extend_existing': True}
    __tablename__ = "users"
    id = db.Column(db.Integer, primary_key=True, index=True)  # 主键，用户id
    username = db.Column(db.String(100))  # 用户名
    password = db.Column(db.String(100))  # 密码
    phone = db.Column(db.String(20))  # 手机号码
    email = db.Column(db.String(20))  # 邮箱
    name = db.Column(db.String(20))  # 姓名
    gender = db.Column(db.String(5))  # 性别
    region = db.Column(db.String(5))  # 所在地区
    introduction = db.Column(db.String(100))  # 个人简介

    def __init__(self, username, password, phone, email, name, gender, region, introduction):
        self.username = username
        self.password = password
        self.phone = phone
        self.email = email
        self.name = name
        self.gender = gender
        self.region = region
        self.introduction = introduction


class UserSQLOperation:
    """
    操作用户数据表的类
    """

    @staticmethod
    def createTable():
        db.create_all()

    @staticmethod
    def insert(username, password, phone, email, name, gender, region, introduction):
        n = db.session.add(Users(username, password, phone, email, name, gender, region, introduction))
        db.session.commit()
        return n

    @staticmethod
    def deleteByUsername(username):
        n = Users.query.filter(Users.username == username).delete()
        db.session.commit()
        return n

    @staticmethod
    def searchByUsername(username):
        return Users.query.filter(Users.username == username).first()

    @staticmethod
    def updateByUsername(username, password="", phone="", email="", name="", gender="", region="", introduction=""):
        if password != "":
            Users.query.filter(Users.username == username).update({'password': password})
        if phone != "":
            Users.query.filter(Users.username == username).update({'phone': phone})
        if email != "":
            Users.query.filter(Users.username == username).update({'email': email})
        if name != "":
            Users.query.filter(Users.username == username).update({'name': name})
        if gender != "":
            Users.query.filter(Users.username == username).update({'gender': gender})
        if region != "":
            Users.query.filter(Users.username == username).update({'region': region})
        if introduction != "":
            Users.query.filter(Users.username == username).update({'introduction': introduction})
        db.session.commit()


if __name__ == "__main__":
    db.create_all()
